package com.telecom.cms.actions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.ncr.teradata.bireport.CommonFunc;
import com.telecom.cms.dao.IdaDAO;
import com.telecom.cms.dao.IdaLogDAO;
import com.telecom.cms.dto.IdaInstanceParam;
import com.telecom.cms.dto.IdaInstanceResult;
import com.telecom.cms.dto.IdaInstanceSql;
import com.telecom.cms.dto.IdaTemplate;
import com.telecom.cms.dto.IdaTemplateAtomParam;
import com.telecom.cms.dto.IdaTemplateAtomSql;
import com.telecom.cms.dto.IdaTemplateInstance;
import com.telecom.cms.dto.SEG_BIZ_ATOM_DEFDTO;
import com.telecom.cms.dto.SysLocLatn;
import com.telecom.cms.service.IdaMgr;
import com.telecom.cms.util.Constant;
import com.telecom.cms.util.CurrentTime;

public class IdaAction extends DispatchAction 
{
	private IdaMgr idamgr;
	
	private void getCommon(HttpServletRequest request){
		List templateList = idamgr.findAllTemplate();
		request.setAttribute("templateList", templateList);
		List instanceList = idamgr.findAllInstance();
		request.setAttribute("instanceList", instanceList);
		
		String templateId = request.getParameter("templateId");
		if (templateId != null && !templateId.equals("")){
			int tid = Integer.parseInt(templateId);
			IdaTemplate template = idamgr.findTemplate(tid);
			if (template != null){
				request.setAttribute("idaTemplate", template);
				IdaTemplate resultTemplate = idamgr.findTemplate(template.getResultTemplateId());
				if (resultTemplate != null)
					request.setAttribute("resultTemplate", resultTemplate);
			}
		}
		String instanceId = request.getParameter("instanceId");
		if (instanceId != null && !instanceId.equals("")){
			int iid = Integer.parseInt(instanceId);
			IdaTemplateInstance instance = idamgr.findInstance(iid);
			if (instance != null){
				request.setAttribute("idaInstance", instance);
			}
		}
	}
	
	public ActionForward idaleft(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		getCommon(request);
		String roleId = (String)request.getSession().getAttribute("User_Auth");
		request.setAttribute("authTemplate", (new IdaDAO()).findTemplateByRoleId(Integer.parseInt(roleId)));
		return mapping.findForward("idaleft");
	}
	
	public ActionForward runIda(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		getCommon(request);
		IdaDAO idadao = new IdaDAO();
		
		StringBuffer paramStr = new StringBuffer();
		paramStr.append("<tr>");
		paramStr.append("<td align='center' width='20%'>基本条件</td>");
		paramStr.append("<td width='80%'>");
		paramStr.append("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
		paramStr.append("<td width='10%'>帐务月：</td>");
		paramStr.append("<td><select name='billingCycleId'>");
		List billingCycleIdList = new ArrayList();
		for (int i = -1; i >= -12; i--){
			String m = CommonFunc.convertDate(CommonFunc.getToday("yyyyMMdd"), "yyyyMMdd", Calendar.MONTH, i).substring(0,6);
			paramStr.append("<option value='" + m + "'>" + m + "</option>");
			billingCycleIdList.add(m);
		}
		request.setAttribute("billingCycleIdList",billingCycleIdList);
		paramStr.append("</select></td>");
		paramStr.append("<td width='10%'>本地网：</td>");
		paramStr.append("<td><select name='latnCd'>");
		List latns = idadao.findLatn((String)request.getSession().getAttribute("Latn_Id"));
		for (int i = 0; i < latns.size(); i++){
			SysLocLatn locLatn = (SysLocLatn)latns.get(i);
			if (locLatn.getLatn_Cd().equalsIgnoreCase("Z"))
				continue;
			paramStr.append("<option value='" + locLatn.getLatn_Cd() + "'>" + locLatn.getLatnname() + "</option>");
		}
		paramStr.append("</select></td>");
		paramStr.append("<td width='50%'>&nbsp;</td>");
		paramStr.append("</table>");
		paramStr.append("</td>");
		paramStr.append("</tr>");
		
		IdaTemplate template = (IdaTemplate)request.getAttribute("idaTemplate");
		List atomList = template.getAtomList();
		Map atomValueMap = idadao.findAtomValueMap();
		if (template.getTemplateTypeId().equals("10")){
			for (int i = 0; i < atomList.size(); i++){
				IdaTemplateAtomParam atom = (IdaTemplateAtomParam)atomList.get(i);
				String pName = String.valueOf(atom.getBizAtomId());
				String pValue = atom.getDefaultValue();
				String pNotEmpty = atom.getIsNotEmpty().equals("10") ? "*&nbsp;" : "";
				String pDisable = atom.getIsFiltOnly().equals("10") ? "disabled" : "";
				if (atom.getIsFiltOnly().equals("10"))
					paramStr.append("<input type='hidden' name='" + pName + "' value='" + pValue + "'>");
				List atomValues = (List)atomValueMap.get(pName);
				paramStr.append("<tr>");
				paramStr.append("<td align='center'>" + pNotEmpty + atom.getBizAtomName() + "</td>");
				paramStr.append("<td>");
				paramStr.append(buildHtmlControl(atom.getShowTypeId(),pName,pValue,pDisable,atomValues,atom.getBizAtomName()));
				paramStr.append("<span id='span" + pName + "' style='color: red'></span>");
				paramStr.append("</td>");
				paramStr.append("</tr>");
			}
		}
		else if (template.getTemplateTypeId().equals("30")){
			for (int i = 0; i < atomList.size(); i++){
				IdaTemplateAtomSql param = (IdaTemplateAtomSql)atomList.get(i);
				String pName = param.getParamName();
				String pValue = param.getDefaultValue();
				String pNotEmpty = param.getIsNotEmpty().equals("10") ? "*&nbsp;" : "";
				String pDisable = param.getIsFiltOnly().equals("10") ? "disabled" : "";
				if (param.getIsFiltOnly().equals("10"))
					paramStr.append("<input type='hidden' name='" + pName + "' value='" + pValue + "'>");
				List atomValues = new ArrayList();
				if (param.getIsMatchAtom().equals("10"))
					atomValues = (List)atomValueMap.get(String.valueOf(param.getBizAtomId()));
				paramStr.append("<tr>");
				paramStr.append("<td align='center'>" + pNotEmpty + param.getParamNameCn() + "</td>");
				paramStr.append("<td>");
				paramStr.append(buildHtmlControl(param.getShowTypeId(),pName,pValue,pDisable,atomValues,param.getParamNameCn()));
				paramStr.append("<span id='span" + pName + "' style='color: red'></span>");
				paramStr.append("</td>");
				paramStr.append("</tr>");
			}
		}
		request.setAttribute("paramStr", paramStr.toString());
		
		request.getSession().setAttribute("AccsLogId", 
				IdaLogDAO.logAccs(((Long)request.getSession().getAttribute("LoginLogId")).longValue(),
				template.getTemplateId(),"11",""));
		
		return mapping.findForward("runIda");
	}
	
	public ActionForward runInstance(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		getCommon(request);
		IdaDAO idadao = new IdaDAO();
		
		StringBuffer paramStr = new StringBuffer();
		paramStr.append("<tr>");
		paramStr.append("<td align='center' width='20%'>基本条件</td>");
		paramStr.append("<td width='80%'>");
		paramStr.append("<table width='100%' border='0' cellspacing='0' cellpadding='0'>");
		paramStr.append("<td width='10%'>帐务月：</td>");
		paramStr.append("<td><select name='billingCycleId'>");
		List billingCycleIdList = new ArrayList();
		for (int i = -1; i >= -12; i--){
			String m = CommonFunc.convertDate(CommonFunc.getToday("yyyyMMdd"), "yyyyMMdd", Calendar.MONTH, i).substring(0,6);
			paramStr.append("<option value='" + m + "'>" + m + "</option>");
			billingCycleIdList.add(m);
		}
		request.setAttribute("billingCycleIdList",billingCycleIdList);
		paramStr.append("</select></td>");
		paramStr.append("<td width='10%'>本地网：</td>");
		paramStr.append("<td><select name='latnCd'>");
		List latns = idadao.findLatn((String)request.getSession().getAttribute("Latn_Id"));
		for (int i = 0; i < latns.size(); i++){
			SysLocLatn locLatn = (SysLocLatn)latns.get(i);
			if (locLatn.getLatn_Cd().equalsIgnoreCase("Z"))
				continue;
			paramStr.append("<option value='" + locLatn.getLatn_Cd() + "'>" + locLatn.getLatnname() + "</option>");
		}
		paramStr.append("</select></td>");
		paramStr.append("<td width='50%'>&nbsp;</td>");
		paramStr.append("</table>");
		paramStr.append("</td>");
		paramStr.append("</tr>");
		
		IdaTemplateInstance instance = (IdaTemplateInstance)request.getAttribute("idaInstance");
		if (instance == null || instance.getInstanceStat().equals("30"))
			return mapping.findForward("runInstance");
		List paramInstList = instance.getParamList();
		IdaTemplate template = idamgr.findTemplate(instance.getTemplateId());
		List atomList = template.getAtomList();
		Map atomValueMap = idadao.findAtomValueMap();
		if (template.getTemplateTypeId().equals("10")){
			for (int i = 0; i < atomList.size(); i++){
				IdaTemplateAtomParam atom = (IdaTemplateAtomParam)atomList.get(i);
				String pName = String.valueOf(atom.getBizAtomId());
				String pValue = "";
				for (int j = 0; j < paramInstList.size(); j++){
					IdaInstanceParam pinst = (IdaInstanceParam)paramInstList.get(j);
					if (pinst.getBizAtomId() == atom.getBizAtomId()){
						pValue = pinst.getParamValue();
						break;
					}
				}
				String pNotEmpty = atom.getIsNotEmpty().equals("10") ? "*&nbsp;" : "";
				String pDisable = atom.getIsFiltOnly().equals("10") ? "disabled" : "";
				if (atom.getIsFiltOnly().equals("10"))
					paramStr.append("<input type='hidden' name='" + pName + "' value='" + pValue + "'>");
				List atomValues = (List)atomValueMap.get(pName);
				paramStr.append("<tr>");
				paramStr.append("<td align='center'>" + pNotEmpty + atom.getBizAtomName() + "</td>");
				paramStr.append("<td>");
				paramStr.append(buildHtmlControl(atom.getShowTypeId(),pName,pValue,pDisable,atomValues,atom.getBizAtomName()));
				paramStr.append("<span id='span" + pName + "' style='color: red'></span>");
				paramStr.append("</td>");
				paramStr.append("</tr>");
			}
		}
		else if (template.getTemplateTypeId().equals("30")){
			for (int i = 0; i < atomList.size(); i++){
				IdaTemplateAtomSql param = (IdaTemplateAtomSql)atomList.get(i);
				String pName = param.getParamName();
				String pValue = "";
				for (int j = 0; j < paramInstList.size(); j++){
					IdaInstanceSql pinst = (IdaInstanceSql)paramInstList.get(j);
					if (pinst.getParamName().equals(param.getParamName())){
						pValue = pinst.getParamValue();
						break;
					}
				}
				String pNotEmpty = param.getIsNotEmpty().equals("10") ? "*&nbsp;" : "";
				String pDisable = param.getIsFiltOnly().equals("10") ? "disabled" : "";
				if (param.getIsFiltOnly().equals("10"))
					paramStr.append("<input type='hidden' name='" + pName + "' value='" + pValue + "'>");
				List atomValues = new ArrayList();
				if (param.getIsMatchAtom().equals("10"))
					atomValues = (List)atomValueMap.get(String.valueOf(param.getBizAtomId()));
				paramStr.append("<tr>");
				paramStr.append("<td align='center'>" + pNotEmpty + param.getParamNameCn() + "</td>");
				paramStr.append("<td>");
				paramStr.append(buildHtmlControl(param.getShowTypeId(),pName,pValue,pDisable,atomValues,param.getParamNameCn()));
				paramStr.append("<span id='span" + pName + "' style='color: red'></span>");
				paramStr.append("</td>");
				paramStr.append("</tr>");
			}
		}
		request.setAttribute("paramStr", paramStr.toString());
		
		request.getSession().setAttribute("AccsLogId", 
				IdaLogDAO.logAccs(((Long)request.getSession().getAttribute("LoginLogId")).longValue(),
				instance.getInstanceId(),"12",String.valueOf(instance.getTemplateId())));
		
		return mapping.findForward("runInstance");
	}
	
	public ActionForward doQuery(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		IdaDAO idadao = new IdaDAO();
		int tid = Integer.parseInt(request.getParameter("templateId"));
		IdaTemplate template = idamgr.findTemplate(tid);
		String billingCycleId = request.getParameter("billingCycleId");
		String latnCd = request.getParameter("latnCd");
		String queryType = request.getParameter("queryType");
		
		String basTable = "";
		String basColumn = "";
		boolean basTableIsCurrent = false;
		if (template.getAnlsTypeId().equals("10")){
			basTable = Constant.getStPara("bastablename");
			basColumn = Constant.getStPara("PrdIdColName");
			if (Constant.getStPara("BasTableIsCurrent").trim().equalsIgnoreCase("YES"))
				basTableIsCurrent = true;
		}
		else if(template.getAnlsTypeId().equals("20")){
			basTable = Constant.getStPara("BasCustTable");
			basColumn = Constant.getStPara("CustIdColName");
			if (Constant.getStPara("BasCustTableIsCurrent").trim().equalsIgnoreCase("YES"))
				basTableIsCurrent = true;
		}
		else ;
		
		StringBuffer sql = new StringBuffer();
		StringBuffer selectStr = new StringBuffer();
		StringBuffer fromStr = new StringBuffer();
		StringBuffer whereStr = new StringBuffer();
		String groupBy = "";
		String orderBy = "";
		Set basTableSet = new TreeSet();
		Set dmnTableSet = new TreeSet();
		List resultAtoms = new ArrayList();
		List paramValues = new ArrayList();
		paramValues.add(new String[]{"帐务月",billingCycleId});
		StringBuffer filtResult = new StringBuffer();
		
		String[] rsAtoms = request.getParameterValues("ObjSelect");
		if (rsAtoms != null){
			Map atomValueMap = idadao.findAtomValueMap();
			String sumStart = queryType.equals("20") ? "SUM(" : "";
			String sumEnd = queryType.equals("20") ? ")" : "";
			selectStr.append("SELECT \n");
			for (int i = 0; i < rsAtoms.length; i++){
				String orderRule = "";
				if (rsAtoms[i].indexOf("#") != -1){
					orderRule = rsAtoms[i].substring(rsAtoms[i].indexOf("#") + 1);
					rsAtoms[i] = rsAtoms[i].substring(0,rsAtoms[i].indexOf("#"));
				}
				
				SEG_BIZ_ATOM_DEFDTO atom = idadao.findAtom(Integer.parseInt(rsAtoms[i]));
				resultAtoms.add(atom);
				String colName = atom.getBAS_TABLE_COL_NAME().trim();
				String tableName = atom.getBAS_TABLE_NAME().trim();
				if (atom.getSRC_TABLE_COL_NAME() != null && !atom.getSRC_TABLE_COL_NAME().trim().equals("")){
					colName = atom.getSRC_TABLE_COL_NAME().trim();
					tableName = atom.getCDE_SRC_TABLE_NAME().trim();
					dmnTableSet.add(tableName + "#" + atom.getBAS_TABLE_NAME().trim() + "#" + atom.getBAS_TABLE_COL_NAME().trim());
				}
				if (i > 0)
					selectStr.append("\t,");
				else
					selectStr.append("\t");
				String atomFlag = atom.getBIZ_ATOM_FLAG().trim();
				if (atomFlag.equalsIgnoreCase("MONEY")){
					selectStr.append(sumStart + tableName + "." + colName + sumEnd + "/100 \n");
				}
				else if (atomFlag.equalsIgnoreCase("TIME")){
					selectStr.append(sumStart + tableName + "." + colName + sumEnd + "/60 \n");
				}
				else if (atomFlag.equalsIgnoreCase("COUNT")){
					selectStr.append(sumStart + tableName + "." + colName + sumEnd + " \n");
				}
				else
					selectStr.append(tableName + "." + colName + " \n");
				
				basTableSet.add(atom.getBAS_TABLE_NAME().trim());
				if (queryType.equals("20")){
					if (!(atomFlag.equalsIgnoreCase("MONEY") || atomFlag.equalsIgnoreCase("TIME") || atomFlag.equalsIgnoreCase("COUNT"))){
						if (groupBy.equals(""))
							groupBy = "GROUP BY " + (i + 1);
						else
							groupBy += "," + (i + 1);
					}
				}
				if (!orderRule.trim().equals("")){
					if (orderBy.equals(""))
						orderBy = "ORDER BY " + (i + 1) + " " + orderRule;
					else
						orderBy += "," + (i + 1) + " " + orderRule;
				}
				
				filtResult.append("<tr><td>" + atom.getBIZ_ATOM_NAME() + "</td><td>");
				if (atomFlag.equalsIgnoreCase("MONEY") || atomFlag.equalsIgnoreCase("TIME") || atomFlag.equalsIgnoreCase("COUNT")){
					filtResult.append(buildHtmlControl("14",String.valueOf(atom.getBIZ_ATOM_ID()),"","",null,""));
				}
				else{
					List atomValues = (List)atomValueMap.get(String.valueOf(atom.getBIZ_ATOM_ID()));
					String showType = atomValues.size() == 0 ? "10" : (atomValues.size() > 10 ? "17" : "13");
					filtResult.append(buildHtmlControl(showType,String.valueOf(atom.getBIZ_ATOM_ID()),"","",atomValues,""));
				}
				filtResult.append("</td></tr>");
			}
			if (!groupBy.equals(""))
				groupBy += " \n";
		}
		
		Map instanceParamValue = new HashMap();
		List paramList = template.getAtomList();
		if (template.getTemplateTypeId().equals("10")){
			boolean isFirstParam = true;
			Map atomValueMap = idadao.findAtomValueMap();
			for (int i = 0; i < paramList.size(); i++){
				IdaTemplateAtomParam param = (IdaTemplateAtomParam)paramList.get(i);
				SEG_BIZ_ATOM_DEFDTO atom = idadao.findAtom(param.getBizAtomId());
				String basTableName = atom.getBAS_TABLE_NAME().trim();
				String basColName = atom.getBAS_TABLE_COL_NAME().trim();
				String preFix = isFirstParam ? "WHERE \t" : "AND \t";
				String c = atom.getBAS_TABLE_COL_TYPE().toUpperCase().indexOf("CHAR") != -1 ? "'" : "";
				String atomFlag = atom.getBIZ_ATOM_FLAG().trim();
				String calc = "";
				if (atomFlag.equalsIgnoreCase("MONEY"))
					calc = "/100";
				else if (atomFlag.equalsIgnoreCase("TIME"))
					calc = "/60";
				
				instanceParamValue.put(String.valueOf(param.getBizAtomId()), request.getParameterValues(String.valueOf(param.getBizAtomId())));
				String[] pValues = request.getParameterValues(String.valueOf(param.getBizAtomId()));
				if (param.getIsNotEmpty().equals("10")){
					if (checkHtmlCtrlIsEmpty(pValues,param.getShowTypeId())){
						request.setAttribute("errorInfo.emptyParamName", param.getBizAtomName());
						return mapping.findForward("idaResult");
					}
				}
				if (param.getShowTypeId().equals("14")){ //between input
					if (pValues[0] != null && !pValues[0].trim().equals("") && pValues[1] != null && !pValues[1].trim().equals("")){
						whereStr.append(preFix + basTableName + "." + basColName + calc + " BETWEEN " + c + pValues[0] + c + " AND " + c + pValues[1] + c + " \n");
						isFirstParam = false;
						String[] pv = new String[]{param.getBizAtomName(),"大于等于" + pValues[0] + " 且 小余等于" + pValues[1]};
						paramValues.add(pv);
					}
					else if (pValues[0] != null && !pValues[0].trim().equals("")){
						whereStr.append(preFix + basTableName + "." + basColName + calc + " >= " + c + pValues[0] + c + " \n");
						isFirstParam = false;
						String[] pv = new String[]{param.getBizAtomName(),"大于等于" + pValues[0]};
						paramValues.add(pv);
					}
					else if (pValues[1] != null && !pValues[1].trim().equals("")){
						whereStr.append(preFix + basTableName + "." + basColName + calc + " <= " + c + pValues[1] + c + " \n");
						isFirstParam = false;
						String[] pv = new String[]{param.getBizAtomName(),"小余等于" + pValues[1]};
						paramValues.add(pv);
					}
					else ;
				}
				else{
					if (pValues != null && pValues.length > 0){
						if (param.getShowTypeId().equals("16")){ //date select
							for (int k = 0; k < pValues.length; k++){
								String[] val = pValues[k].split("-");
								if (val != null && val.length == 3)
									pValues[k] = val[0] + val[1] + val[2];
							}
						}
						List atomValues = (List)atomValueMap.get(String.valueOf(atom.getBIZ_ATOM_ID()));
						String valueStr = "";
						String valueStrCn = "";
						for (int j = 0; j < pValues.length; j++){
							if (pValues[j].trim().equals(""))
								continue;
							if (j > 0){
								valueStr += ",";
								valueStrCn += "，";
							}
							if (param.getIsLikeMatch().equals("10"))
								valueStr += c + "%" + pValues[j] + "%" + c;
							else
								valueStr += c + pValues[j] + c;
							for (int k = 0; k < atomValues.size(); k++){
								String[] value = (String[])atomValues.get(k);
								if (value[0].equalsIgnoreCase(pValues[j])){
									if (value[2].equals(""))
										valueStrCn += value[1];
									else
										valueStrCn += value[1] + "－" + value[2];
								}
							}
						}
						if (!valueStr.equals("")){
							if ((atomFlag.equalsIgnoreCase("MONEY") || atomFlag.equalsIgnoreCase("TIME") || atomFlag.equalsIgnoreCase("COUNT"))
									&& (param.getShowTypeId().equals("11") || param.getShowTypeId().equals("13") || param.getShowTypeId().equals("17"))){
								String[] values = valueStrCn.split("，");
								if (values.length > 1){
									whereStr.append(preFix + "(\n");
									for (int j = 0; j < values.length; j++){
										String[] val = values[j].split("－");
										if (j == 0)
											whereStr.append("\t\t");
										else
											whereStr.append("\t\tOR ");
										whereStr.append(basTableName + "." + basColName + calc + " BETWEEN " + val[0] + " AND " + val[1] + " \n");
									}
									whereStr.append("\t)\n");
								}
								else{
									String[] val = values[0].split("－");
									whereStr.append(preFix + basTableName + "." + basColName + calc + " BETWEEN " + val[0] + " AND " + val[1] + " \n");
								}
							}
							else{
								if (param.getIsLikeMatch().equals("10")){
									if (valueStr.indexOf("','") != -1)
										whereStr.append(preFix + basTableName + "." + basColName + calc + " LIKE ANY (" + valueStr + ") \n");
									else
										whereStr.append(preFix + basTableName + "." + basColName + calc + " LIKE (" + valueStr + ") \n");
								}
								else
									whereStr.append(preFix + basTableName + "." + basColName + calc + " IN (" + valueStr + ") \n");
							}
							isFirstParam = false;
							if (valueStrCn.equals(""))
								valueStrCn = valueStr;
							String[] pv = new String[]{param.getBizAtomName(),valueStrCn};
							paramValues.add(pv);
						}
					}
				}
				
				basTableSet.add(basTableName);
			}
			if (!basTableIsCurrent){
				String preFix = isFirstParam ? "WHERE \t" : "AND \t";
				whereStr.append(preFix + basTable + ".Billing_Cycle_Id = '" + billingCycleId + "' \n");
			}
		}
		else if (template.getTemplateTypeId().equals("30")){
			String confSql = template.getSqlStmt() + "  ";
			String colName = "";
			if (template.getNbrType().equals("10"))
				colName = "Accs_Nbr";
			else if (template.getNbrType().equals("20"))
				colName = "Prd_Inst_Id";
			else if (template.getNbrType().equals("30"))
				colName = "Cust_Id";
			whereStr.append("WHERE\t" + basTable + "." + colName + " IN \n(\n");
			
			Map atomValueMap = idadao.findAtomValueMap();
			for (int i = 0; i < paramList.size(); i++){
				IdaTemplateAtomSql param = (IdaTemplateAtomSql)paramList.get(i);
				String c = param.getValueTypeId().toUpperCase().indexOf("CHAR") != -1 ? "'" : "";
				String valueStr = "";
				String valueStrCn = "";
				
				instanceParamValue.put(param.getParamName(), request.getParameterValues(param.getParamName()));
				String[] pValues = request.getParameterValues(String.valueOf(param.getParamName()));
				if (param.getIsNotEmpty().equals("10")){
					if (checkHtmlCtrlIsEmpty(pValues,param.getShowTypeId())){
						request.setAttribute("errorInfo.emptyParamName", param.getParamNameCn());
						return mapping.findForward("idaResult");
					}
				}
				if (pValues != null && pValues.length > 0){
					if (param.getShowTypeId().equals("16")){ //date select
						for (int k = 0; k < pValues.length; k++){
							String[] val = pValues[k].split("-");
							if (val != null && val.length == 3)
								pValues[k] = val[0] + val[1] + val[2];
						}
					}
					List atomValues = new ArrayList();
					if (param.getIsMatchAtom().equals("10"))
						atomValues = (List)atomValueMap.get(String.valueOf(param.getBizAtomId()));
					for (int j = 0; j < pValues.length; j++){
						if (pValues[j].trim().equals(""))
							continue;
						if (j > 0){
							valueStr += ",";
							valueStrCn += "，";
						}
						valueStr += c + pValues[j] + c;
						for (int k = 0; k < atomValues.size(); k++){
							String[] value = (String[])atomValues.get(k);
							if (value[0].equalsIgnoreCase(pValues[j])){
								if (value[2].equals(""))
									valueStrCn += value[1];
								else
									valueStrCn += value[1] + "－" + value[2];
							}
						}
						if (atomValues.size() == 0){
							valueStrCn += pValues[j];
						}
					}
				}
				if (valueStr.equals("")){
					if (c.equals("'"))
						valueStr = c + "" + c;
					else{
						valueStr = "0";
						valueStrCn = "0";
					}
				}
				int pLen = param.getParamName().length();
				int pIdx = confSql.indexOf(param.getParamName());
				confSql = confSql.substring(0,pIdx) + "" + valueStr + "" + confSql.substring(pIdx + pLen);
				String[] pv = new String[]{param.getParamNameCn(),valueStrCn};
				paramValues.add(pv);
			}
			whereStr.append(confSql + "\n)\n");
			if (!basTableIsCurrent){
				whereStr.append("AND \t" + basTable + ".Billing_Cycle_Id = '" + billingCycleId + "' \n");
			}
		}
		
		String mmTable = "";
		String multiMonthStr = "";
		String viewMultiMonth = request.getParameter("viewMultiMonth");
		if (viewMultiMonth != null && viewMultiMonth.equalsIgnoreCase("T")){
			String[] viewMonth = request.getParameterValues("viewMonth");
			if (viewMonth != null && viewMonth.length > 0){
				for (int i = 0; i < viewMonth.length; i++){
					if (i > 0)
						multiMonthStr += ",";
					multiMonthStr += "'" + viewMonth[i] + "'";
				}
			}
		}
		
		fromStr.append("FROM\t\t" + basTable + "\n");
		Object[] tables = basTableSet.toArray();
		for (int i = 0; i < tables.length; i++){
			if (tables[i].toString().equalsIgnoreCase(basTable)){
				continue;
			}
			else{
				fromStr.append("LEFT JOIN\t" + tables[i] + "\n");
				fromStr.append("ON\t\t" + basTable + "." + basColumn + " = " + tables[i] + "." + basColumn + " \n");
				if (Constant.getStPara("NoMonthJoinTable").indexOf(tables[i].toString()) == -1){
					if (multiMonthStr.trim().equals("")){
						fromStr.append("AND\t\t" + tables[i] + ".Billing_Cycle_Id = '" + billingCycleId + "' \n");
					}
					else{
						fromStr.append("AND\t\t" + tables[i] + ".Billing_Cycle_Id IN (" + multiMonthStr + ") \n");
						if (mmTable.trim().equals("")){
							mmTable = tables[i].toString();
							
							//if view multi-month and no Billing_Cycle_Id in resultset, auto add this atom
							boolean hasBillingCycleId = false;
							for (int j = 0; j < resultAtoms.size(); j++){
								SEG_BIZ_ATOM_DEFDTO tmpAtom = (SEG_BIZ_ATOM_DEFDTO)resultAtoms.get(j);
								if (tmpAtom.getBAS_TABLE_COL_NAME().trim().equals("Billing_Cycle_Id")){
									hasBillingCycleId = true;
									break;
								}
							}
							if (!hasBillingCycleId){
								selectStr.append("\t," + mmTable + ".Billing_Cycle_Id \n");
								SEG_BIZ_ATOM_DEFDTO monthAtom = new SEG_BIZ_ATOM_DEFDTO();
								monthAtom.setBIZ_ATOM_NAME("帐务月");
								resultAtoms.add(monthAtom);
								if (queryType.equals("20")){
									if (groupBy.equals(""))
										groupBy = "GROUP BY " + resultAtoms.size() + " \n";
									else
										groupBy = groupBy.substring(0,groupBy.indexOf("\n")).trim() + "," + resultAtoms.size() + " \n";
								}
								if (orderBy.equals(""))
									orderBy = "ORDER BY " + resultAtoms.size() + " desc";
								else
									orderBy += "," + resultAtoms.size() + " desc";
							}
						}
						else
							fromStr.append("AND\t\t" + tables[i] + ".Billing_Cycle_Id = " + mmTable + ".Billing_Cycle_Id \n");
					}
				}
			}
		}
		Object[] dmnTables = dmnTableSet.toArray();
		for (int i = 0; i < dmnTables.length; i++){
			String[] dt = dmnTables[i].toString().split("#");
			fromStr.append("LEFT JOIN\t" + dt[0] + "\n");
			fromStr.append("ON\t\t" + dt[1] + "." + dt[2] + " = " + dt[0] + "." + dt[2] + " \n");
		}
		
		sql.append(selectStr.toString());
		sql.append(fromStr.toString());
		sql.append(whereStr.toString());
		sql.append(groupBy);
		sql.append(orderBy);
		String idaSql = sql.toString();
		idaSql = idaSql.replaceAll("_Z ", "_"+latnCd+" ");
		idaSql = idaSql.replaceAll("_Z\\.", "_"+latnCd+".");
		idaSql = idaSql.replaceAll("_Z,", "_"+latnCd+",");
		
		int pageNo = 1;
		int pageSize = 100;
		String startTime = CurrentTime.getCurrentTime();
		List idaData = idadao.idaQuery(idaSql, pageNo, pageSize, true);
		String endTime = CurrentTime.getCurrentTime();
		int rowCount = ((Integer)idaData.get(0)).intValue();
		int pageCount = rowCount % pageSize == 0 ? rowCount / pageSize : rowCount / pageSize + 1;
		idaData.remove(0);
		
		request.setAttribute("idaData", idaData);
		request.getSession().setAttribute("idaSql", idaSql);
		request.getSession().setAttribute("resultAtoms", resultAtoms);
		request.getSession().setAttribute("paramValues", paramValues);
		request.getSession().setAttribute("filtResult", filtResult.toString());
		request.getSession().setAttribute("pageNo", new Integer(pageNo));
		request.getSession().setAttribute("pageCount", new Integer(pageCount));
		request.getSession().setAttribute("rowCount", new Integer(rowCount));
		request.getSession().setAttribute("idaLatnCd", latnCd);
		request.getSession().removeAttribute("resultFiltSql");
		request.getSession().setAttribute("instanceResultAtoms", request.getParameterValues("ObjSelect"));
		request.getSession().setAttribute("instanceParamValues", instanceParamValue);
		request.getSession().setAttribute("instanceTemplateId", String.valueOf(tid));
		
		IdaLogDAO.logExecute(((Long)request.getSession().getAttribute("AccsLogId")).longValue(), "11", idaSql, rowCount, startTime, endTime, "");
		return mapping.findForward("idaResult");
	}
	
	public ActionForward doPagingQuery(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		String idaSql = (String)request.getSession().getAttribute("idaSql");
		int pageNo = ((Integer)request.getSession().getAttribute("pageNo")).intValue();
		int pageCount = ((Integer)request.getSession().getAttribute("pageCount")).intValue();
		int pageSize = 100;
		String paging = request.getParameter("paging");
		if (paging.equals("first")) 
			pageNo = 1;
		else if (paging.equals("previous")) 
			pageNo = pageNo - 1 < 1 ? 1 : pageNo - 1;
		else if (paging.equals("next")) 
			pageNo = pageNo + 1 > pageCount ? pageCount : pageNo + 1;
		else if (paging.equals("last")) 
			pageNo = pageCount;
		
		if (request.getSession().getAttribute("resultFiltSql") != null){
			String resultFiltSql = (String)request.getSession().getAttribute("resultFiltSql");
			if (idaSql.indexOf("GROUP BY") == -1 && idaSql.indexOf("ORDER BY") == -1){
				idaSql += resultFiltSql;
			}
			else{
				int idx = 0;
				if (idaSql.indexOf("GROUP BY") != -1 && idaSql.indexOf("ORDER BY") != -1)
					idx = (idaSql.indexOf("GROUP BY") > idaSql.indexOf("ORDER BY")) ? idaSql.indexOf("ORDER BY") : idaSql.indexOf("GROUP BY");
				else if (idaSql.indexOf("GROUP BY") != -1){
					idx = idaSql.indexOf("GROUP BY");
				}
				else if (idaSql.indexOf("ORDER BY") != -1){
					idx = idaSql.indexOf("ORDER BY");
				}
				else ;
				idaSql = idaSql.substring(0,idx) + resultFiltSql + idaSql.substring(idx);
			}
		}
		
		String startTime = CurrentTime.getCurrentTime();
		List idaData = (new IdaDAO()).idaQuery(idaSql, pageNo, pageSize, false);
		String endTime = CurrentTime.getCurrentTime();
		request.setAttribute("idaData", idaData);
		request.getSession().setAttribute("pageNo", new Integer(pageNo));
		
		IdaLogDAO.logExecute(((Long)request.getSession().getAttribute("AccsLogId")).longValue(), "12", idaSql, ((Integer)request.getSession().getAttribute("rowCount")).intValue(), startTime, endTime, "paging");
		return mapping.findForward("idaResult");
	}
	
	public ActionForward doQueryInResult(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		IdaDAO idadao = new IdaDAO();
		StringBuffer resultFiltSql = new StringBuffer();
		StringBuffer filtResult = new StringBuffer();
		Map atomValueMap = idadao.findAtomValueMap();
		List resultAtoms = (List)request.getSession().getAttribute("resultAtoms");
		for (int i = 0; i < resultAtoms.size(); i++){
			SEG_BIZ_ATOM_DEFDTO atom = (SEG_BIZ_ATOM_DEFDTO)resultAtoms.get(i);
			if (atom.getBIZ_ATOM_ID() < 1) //auto added "Billing_Cycle_Id" when view multi-month, continue
				continue;
			String basTableName = atom.getBAS_TABLE_NAME().trim();
			String basColName = atom.getBAS_TABLE_COL_NAME().trim();
			String c = atom.getBAS_TABLE_COL_TYPE().toUpperCase().indexOf("CHAR") != -1 ? "'" : "";
			String atomFlag = atom.getBIZ_ATOM_FLAG().trim();
			String calc = "";
			if (atomFlag.equalsIgnoreCase("MONEY"))
				calc = "/100";
			else if (atomFlag.equalsIgnoreCase("TIME"))
				calc = "/60";
			
			String pValueHtml = "";
			String[] pValues = request.getParameterValues(String.valueOf(atom.getBIZ_ATOM_ID()));
			String showType = "13";
			if (atomFlag.equalsIgnoreCase("MONEY") || atomFlag.equalsIgnoreCase("TIME") || atomFlag.equalsIgnoreCase("COUNT"))
				showType = "14";
			if (showType.equals("14")){ //between input
				if (pValues[0] != null && !pValues[0].trim().equals("") && pValues[1] != null && !pValues[1].trim().equals("")){
					resultFiltSql.append("AND \t" + basTableName + "." + basColName + calc + " BETWEEN " + c + pValues[0] + c + " AND " + c + pValues[1] + c + " \n");
					pValueHtml = pValues[0].trim() + "，" + pValues[1].trim();
				}
				else if (pValues[0] != null && !pValues[0].trim().equals("")){
					resultFiltSql.append("AND \t" + basTableName + "." + basColName + calc + " >= " + c + pValues[0] + c + " \n");
					pValueHtml = pValues[0].trim() + "，" + "";
				}
				else if (pValues[1] != null && !pValues[1].trim().equals("")){
					resultFiltSql.append("AND \t" + basTableName + "." + basColName + calc + " <= " + c + pValues[1] + c + " \n");
					pValueHtml = "" + "，" + pValues[1].trim();
				}
				else ;
			}
			else{	//check box or text box
				if (pValues != null && pValues.length > 0){
					String valueStr = "";
					for (int j = 0; j < pValues.length; j++){
						if (pValues[j].trim().equals(""))
							continue;
						if (j > 0){
							valueStr += ",";
							pValueHtml += "，";
						}
						valueStr += c + pValues[j] + c;
						pValueHtml += pValues[j];
					}
					if (!valueStr.equals("")){
						resultFiltSql.append("AND \t" + basTableName + "." + basColName + calc + " IN (" + valueStr + ") \n");
					}
				}
			}
			
			filtResult.append("<tr><td>" + atom.getBIZ_ATOM_NAME() + "</td><td>");
			if (atomFlag.equalsIgnoreCase("MONEY") || atomFlag.equalsIgnoreCase("TIME") || atomFlag.equalsIgnoreCase("COUNT")){
				filtResult.append(buildHtmlControl(showType,String.valueOf(atom.getBIZ_ATOM_ID()),pValueHtml,"",null,""));
			}
			else{
				List atomValues = (List)atomValueMap.get(String.valueOf(atom.getBIZ_ATOM_ID()));
				showType = atomValues.size() == 0 ? "10" : (atomValues.size() > 10 ? "17" : "13");
				filtResult.append(buildHtmlControl(showType,String.valueOf(atom.getBIZ_ATOM_ID()),pValueHtml,"",atomValues,""));
			}
			filtResult.append("</td></tr>");
		}
		
		String latnCd = (String)request.getSession().getAttribute("idaLatnCd");
		String resultSql = resultFiltSql.toString();
		resultSql = resultSql.replaceAll("_Z ", "_"+latnCd+" ");
		resultSql = resultSql.replaceAll("_Z\\.", "_"+latnCd+".");
		resultSql = resultSql.replaceAll("_Z,", "_"+latnCd+",");
		request.getSession().setAttribute("resultFiltSql", resultSql);
		request.getSession().setAttribute("filtResult", filtResult.toString());
		
		String idaSql = (String)request.getSession().getAttribute("idaSql");
		if (idaSql.indexOf("GROUP BY") == -1 && idaSql.indexOf("ORDER BY") == -1){
			idaSql += resultSql;
		}
		else{
			int idx = 0;
			if (idaSql.indexOf("GROUP BY") != -1 && idaSql.indexOf("ORDER BY") != -1)
				idx = (idaSql.indexOf("GROUP BY") > idaSql.indexOf("ORDER BY")) ? idaSql.indexOf("ORDER BY") : idaSql.indexOf("GROUP BY");
			else if (idaSql.indexOf("GROUP BY") != -1){
				idx = idaSql.indexOf("GROUP BY");
			}
			else if (idaSql.indexOf("ORDER BY") != -1){
				idx = idaSql.indexOf("ORDER BY");
			}
			else ;
			idaSql = idaSql.substring(0,idx) + resultSql + idaSql.substring(idx);
		}
		
		int pageNo = 1;
		int pageSize = 100;
		String startTime = CurrentTime.getCurrentTime();
		List idaData = idadao.idaQuery(idaSql, pageNo, pageSize, true);
		String endTime = CurrentTime.getCurrentTime();
		int rowCount = ((Integer)idaData.get(0)).intValue();
		int pageCount = rowCount % pageSize == 0 ? rowCount / pageSize : rowCount / pageSize + 1;
		idaData.remove(0);
		
		request.setAttribute("idaData", idaData);
		request.getSession().setAttribute("pageNo", new Integer(pageNo));
		request.getSession().setAttribute("pageCount", new Integer(pageCount));
		request.getSession().setAttribute("rowCount", new Integer(rowCount));
		
		IdaLogDAO.logExecute(((Long)request.getSession().getAttribute("AccsLogId")).longValue(), "13", idaSql, rowCount, startTime, endTime, "search in result");
		return mapping.findForward("idaResult");
	}
	
	private String buildHtmlControl(String showType,String pName,String pValue,String pDisable,List atomValues,String pNameCn){
		String[] pvs = pValue.split("，");
		StringBuffer control = new StringBuffer();
		if (showType.equals("10")){ //text
			control.append("<input type='text' name='" + pName + "' value='" + pValue + "' " + pDisable + ">");
		}
		else if (showType.equals("11")){ //select
			control.append("<select name='" + pName + "' " + pDisable + ">");
			control.append("<option value=''>请选择</option>");
			for (int j = 0; j < atomValues.size(); j++){
				String[] value = (String[])atomValues.get(j);
				if (value[2].equals(""))
					control.append("<option value='" + value[0] + "' " + (pValue.equals(value[0]) ? "selected" : "") + ">" + value[1] + "</option>");
				else
					control.append("<option value='" + value[0] + "' " + (pValue.equals(value[0]) ? "selected" : "") + ">" + value[1] + "－" + value[2] + "</option>");
			}
			control.append("</select>");
		}
		else if (showType.equals("12")){ //radio
			for (int j = 0; j < atomValues.size(); j++){
				String[] value = (String[])atomValues.get(j);
				control.append("<input type='radio' name='" + pName + "' value='" + value[0] + "' " + (pValue.equals(value[0]) ? "checked " : " ") + pDisable + ">" + value[1] + "&nbsp;&nbsp;");
			}
		}
		else if (showType.equals("13")){ //checkbox
			for (int j = 0; j < atomValues.size(); j++){
				String[] value = (String[])atomValues.get(j);
				String checked = " ";
				for (int k = 0; k < pvs.length; k++){
					if (pvs[k].equals(value[0])){
						checked = "checked ";
						break;
					}
				}
				if (value[2].equals(""))
					control.append("<input type='checkbox' name='" + pName + "' value='" + value[0] + "' " + checked + pDisable + ">" + value[1] + "&nbsp;&nbsp;");
				else
					control.append("<input type='checkbox' name='" + pName + "' value='" + value[0] + "' " + checked + pDisable + ">" + value[1] + "－" + value[2] + "&nbsp;&nbsp;");
			}
		}
		else if (showType.equals("14")){ //between text input
			if (pvs.length < 1){
				control.append("<input type='text' name='" + pName + "' value='" + "" + "' " + pDisable + " size='5'> 至 ");
				control.append("<input type='text' name='" + pName + "' value='" + "" + "' " + pDisable + " size='5'>");
			}
			else if (pvs.length < 2){
				control.append("<input type='text' name='" + pName + "' value='" + pvs[0] + "' " + pDisable + " size='5'> 至 ");
				control.append("<input type='text' name='" + pName + "' value='" + "" + "' " + pDisable + " size='5'>");
			}
			else{
				control.append("<input type='text' name='" + pName + "' value='" + pvs[0] + "' " + pDisable + " size='5'> 至 ");
				control.append("<input type='text' name='" + pName + "' value='" + pvs[1] + "' " + pDisable + " size='5'>");
			}
		}
		else if (showType.equals("15")){ //tree
			control.append("<a href=\"javascript:showHiddenDiv('div" + pName + "');\">请选择（单击可显示或隐藏选项）</a>");
			control.append("<div style='display: none' id='div" + pName + "'>");
			control.append("<script>");
			control.append("var Tree" + pNameCn + " = new dTree('Tree" + pNameCn + "');");
			for (int j = 0; j < atomValues.size(); j++){
				String[] value = (String[])atomValues.get(j);
				String checked = " ";
				for (int k = 0; k < pvs.length; k++){
					if (pvs[k].equals(value[0])){
						checked = "checked ";
						break;
					}
				}
				control.append("Tree" + pNameCn + ".add('" + value[0] + "','" + value[1] + "',");
				control.append("\"<input type='checkbox' " +
					"name='" + pName + "' id='" + "Tree" + pNameCn + j + "' value='" + value[0] + "' " +
					"onclick='changeChild(Tree" + pNameCn + "," + "Tree" + pNameCn + j + ");" +
					"changeParent(Tree" + pNameCn + "," + "Tree" + pNameCn + j + ");' " + pDisable +
					" " + checked + ">" + value[2] + "\");");
			}
			control.append("document.write(Tree" + pNameCn + ");");
			control.append("</script>");
			control.append("</div>");
		}
		else if (showType.equals("16")){ //date select
			control.append("<input type='text' id='" + pName + "' name='" + pName + "' value='" + pValue + "' " + pDisable + " " +
					"onfocus=\"show_cele_date('" + pName + "','','','" + pName + "')\">");
		}
		else if (showType.equals("17")){ //div list checkbox
			control.append("<div style='height: 100px; overflow-y: auto;'>");
			for (int j = 0; j < atomValues.size(); j++){
				String[] value = (String[])atomValues.get(j);
				String checked = " ";
				for (int k = 0; k < pvs.length; k++){
					if (pvs[k].equals(value[0])){
						checked = "checked ";
						break;
					}
				}
				if (j > 0) control.append("<br>");
				if (value[2].equals(""))
					control.append("<input type='checkbox' name='" + pName + "' value='" + value[0] + "' " + checked + pDisable + ">" + value[1] + "&nbsp;&nbsp;");
				else
					control.append("<input type='checkbox' name='" + pName + "' value='" + value[0] + "' " + checked + pDisable + ">" + value[1] + "－" + value[2] + "&nbsp;&nbsp;");
			}
			control.append("</div>");
		}
		else ;
		return control.toString();
	}
	
	private boolean checkHtmlCtrlIsEmpty(String[] pValues, String showType){
		if (pValues == null || pValues.length == 0)		//12,13,15,17
			return true;
		if (showType.equals("10") || showType.equals("11") || showType.equals("16")){
			if (pValues[0].trim().equals(""))
				return true;
		}
		if (showType.equals("14")){
			if (pValues[0].trim().equals("") && pValues[1].trim().equals(""))
				return true;
		}
		
		return false;
	}
	
	public ActionForward saveInstance(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		IdaDAO idadao = new IdaDAO();
		String userId = ((Integer)request.getSession().getAttribute("User_Id")).toString();
		int tid = Integer.parseInt(request.getParameter("templateId"));
		IdaTemplate template = idamgr.findTemplate(tid);
		
		String rewriteInst = request.getParameter("rewriteInst");
		String deleteInst = request.getParameter("deleteInst");
		if (deleteInst != null && deleteInst.equals("T")){
			idadao.deleteInstance(template,userId);
			return mapping.findForward("saveInstance");
		}
		if (rewriteInst == null)
			rewriteInst = "F";
		String fromResultPage = request.getParameter("fromResultPage");
		if (fromResultPage == null)
			fromResultPage = "F";
		
		IdaTemplateInstance tinst = new IdaTemplateInstance();
		tinst.setTemplateId(tid);
		tinst.setInstanceName(request.getParameter("instanceName"));
		tinst.setInstanceStat("10");
		tinst.setUserId(userId);
		tinst.setInstanceId(idadao.insertInstance(tinst,rewriteInst));
		
		String[] rsAtoms = request.getParameterValues("ObjSelect");
		if (fromResultPage.equals("T"))
			rsAtoms = (String[])request.getSession().getAttribute("instanceResultAtoms");
		if (rsAtoms != null){
			for (int i = 0; i < rsAtoms.length; i++){
				IdaInstanceResult instRs = new IdaInstanceResult();
				String orderRule = "";
				if (rsAtoms[i].indexOf("#") != -1){
					orderRule = rsAtoms[i].substring(rsAtoms[i].indexOf("#") + 1);
					rsAtoms[i] = rsAtoms[i].substring(0,rsAtoms[i].indexOf("#"));
				}
				SEG_BIZ_ATOM_DEFDTO atom = idadao.findAtom(Integer.parseInt(rsAtoms[i]));
				instRs.setBizAtomId(atom.getBIZ_ATOM_ID());
				instRs.setBizAtomName(atom.getBIZ_ATOM_NAME());
				if (atom.getVALUE_TYPE_ID() == 1 || atom.getVALUE_TYPE_ID() == 100)
					instRs.setIsDimension("20");
				else
					instRs.setIsDimension("10");
				instRs.setInstanceId(tinst.getInstanceId());
				instRs.setResultOrderRule(orderRule);
				instRs.setDisplayId(i + 1);
				idadao.insertInstanceResult(instRs);
			}
		}
		
		Map instanceParamValues = null;
		if (fromResultPage.equals("T"))
			instanceParamValues = (Map)request.getSession().getAttribute("instanceParamValues");
		List paramList = template.getAtomList();
		if (template.getTemplateTypeId().equals("10")){
			for (int i = 0; i < paramList.size(); i++){
				IdaTemplateAtomParam param = (IdaTemplateAtomParam)paramList.get(i);
				String[] pValues = request.getParameterValues(String.valueOf(param.getBizAtomId()));
				if (fromResultPage.equals("T"))
					pValues = (String[])instanceParamValues.get(String.valueOf(param.getBizAtomId()));
				String valueStr = "";
				if (pValues != null){
					for (int j = 0; j < pValues.length; j++){
						if (j > 0)
							valueStr += "，";
						valueStr += pValues[j];
					}
				}
				IdaInstanceParam instParam = new IdaInstanceParam();
				instParam.setInstanceId(tinst.getInstanceId());
				instParam.setBizAtomId(param.getBizAtomId());
				instParam.setParamValue(valueStr);
				idadao.insertInstanceParam(instParam);
			}
		}
		else if (template.getTemplateTypeId().equals("30")){
			for (int i = 0; i < paramList.size(); i++){
				IdaTemplateAtomSql param = (IdaTemplateAtomSql)paramList.get(i);
				String[] pValues = request.getParameterValues(String.valueOf(param.getParamName()));
				if (fromResultPage.equals("T"))
					pValues = (String[])instanceParamValues.get(String.valueOf(param.getParamName()));
				String valueStr = "";
				if (pValues != null){
					for (int j = 0; j < pValues.length; j++){
						if (j > 0)
							valueStr += "，";
						valueStr += pValues[j];
					}
				}
				IdaInstanceSql instSql = new IdaInstanceSql();
				instSql.setInstanceId(tinst.getInstanceId());
				instSql.setParamName(param.getParamName());
				instSql.setParamValue(valueStr);
				idadao.insertInstanceSql(instSql);
			}
		}
		
		return mapping.findForward("saveInstance");
	}
	
	public ActionForward deleteInstance(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {
		IdaDAO idadao = new IdaDAO();
		String instId = request.getParameter("instId");
		idadao.deleteInstance(Integer.parseInt(instId));
		
		return mapping.findForward("saveInstance");
	}
	
	public IdaMgr getIdamgr(){
		return idamgr;
	}
	public void setIdamgr(IdaMgr p_idamgr){
		idamgr = p_idamgr;
	}
}